<?php

namespace app\api\controller;

use app\admin\model\Card;
use app\admin\model\Cart;
use app\admin\model\Coupon;
use app\admin\model\Goods;
use app\admin\model\User as UserModel;
use app\admin\model\UserAddress;
use app\admin\model\UserCard;
use app\admin\model\UserCardOrder;
use app\admin\model\UserCoupon;
use app\admin\model\UserMoneyLog;
use app\admin\model\UserScoreLog;
use app\admin\model\Wechat;
use app\admin\model\Wechat as WechatModel;
use app\admin\model\Withdrawal;
use app\common\facade\Token;
use app\common\controller\Frontend;
use ba\Random;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Exception;
use Kkokk\Poster\PosterManager;
use think\db\BaseQuery;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Db;
use think\facade\Validate;

class User extends Frontend
{
    protected $noNeedLogin = ['checkIn', 'logout', 'card', 'getAbout', 'mpLogin', 'appLogin'];

    protected $noNeedPermission = ['index'];

    public function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        $userInfo = $this->auth->getUserInfo();
        // $menus = $this->auth->getMenus();
        // if (!$menus) {
        //     $this->error(__('No action available, please contact the administrator~'));
        // }
        //
        // $userMenus = [];
        // foreach ($menus as $menu) {
        //     if ($menu['type'] == 'menu_dir') {
        //         $userMenus[] = $menu;
        //     }
        // }
        $this->success('', [
            'userInfo' => $userInfo,
            // 'menus'    => $userMenus,
        ]);
    }

    /**
     * 会员签入(登录和注册)
     */
    public function checkIn()
    {
        $openMemberCenter = Config::get('buildadmin.open_member_center');
        if (!$openMemberCenter) {
            $this->error(__('Member center disabled'));
        }

        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'routeName' => 'user',
                'routePath' => '/user',
            ], 302);
        }

        if ($this->request->isPost()) {
            $params = $this->request->post([
                'type', 'email', 'mobile', 'username', 'password', 'keep', 'captcha', 'captchaId', 'smscode',
            ]);
            $params['keep'] = $params['keep'] ?? 0;
            if ($params['type'] != 'login' && $params['type'] != 'register') {
                $this->error(__('Unknown operation'));
            }

            // $captchaObj = new Captcha();
            // if (!$captchaObj->check($params['captcha'], $params['captchaId'])) {
            //     $this->error(__('Please enter the correct verification code'));
            // }

            $res = false;
            if ($params['type'] == 'login') {
                try {
                    $res = $this->auth->login($params['mobile'], $params['password'], (bool)$params['keep']);
                } catch (DataNotFoundException $e) {
                    $msg = $e->getMessage();
                    $this->error($msg);
                } catch (ModelNotFoundException $e) {
                    $msg = $e->getMessage();
                    $this->error($msg);
                } catch (DbException $e) {
                    $msg = $e->getMessage();
                    $this->error($msg);
                }
            } elseif ($params['type'] == 'register') {
                // 校验验证码
                // $code = $params['smscode'];
                // $cache = cache('register' . $params['mobile']);
                // if ($cache != $code) $this->error('验证码错误，请重新发送');
                // // 删除缓存
                // cache('register' . $params['mobile'], null);
                $res = $this->auth->register($params['mobile'], $params['password'], $params['mobile']);
            }

            if (isset($res) && $res === true) {
                $this->success(__('Login succeeded!'), [
                    'userinfo' => $this->auth->getUserInfo(),
                    'routePath' => '/user',
                ]);
            }
            if ($res === true) {
                $userinfo = $this->auth->getUserInfo();
                unset($userinfo['email']);
                unset($userinfo['lastlogintime']);
                unset($userinfo['lastloginip']);
                unset($userinfo['jointime']);
                unset($userinfo['motto']);
                $this->success(__('Login succeeded!'), $userinfo);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: __('Check in failed, please try again or contact the website administrator~');
                $this->error($msg);
            }
        }

        $this->success('', [
            'accountVerificationType' => get_account_verification_type(),
        ]);
    }

    public function logout()
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refresh_token', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success();
        }
    }

    public function modify(UserModel $user)
    {
        $param = $this->request->post([
            'avatar',
            'nickname',
            'mobile',
            'pay_password',
            'real_name',
            'idnumber',
            'idcard_front',
            'idcard_back',
            'drive_front',
            'drive_back',
        ]);
        $validate = Validate::rule([
            'avatar' => 'url',
            'mobile' => 'mobile',
            'pay_password' => 'number',
        ])->message([
            'avatar' => '头像地址不完整',
            'mobile' => '手机号码不合法',
            'pay_password' => '请输入有效的支付密码',
        ]);
        if (!$validate->check($param)) $this->error($validate->getError());
        $user = $user->find($this->auth->getUserId());
        $data = [];
        foreach ($param as $k => $v) {
            if ($param[$k]) {
                if ($k == 'pay_password') {
                    $data[$k] = md5($v);
                } else {
                    $data[$k] = $v;
                }
            }
        }
        $user->save($data);
        $this->success('修改成功');
    }

    /**
     * @param UserCard $card
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function card(UserCard $card)
    {
        $list = $card
            ->where(['switch' => 1])
            ->order('weight asc, id asc')
            ->hidden(['switch', 'createtime', 'updatetime', 'delete_time'])
            ->select();
        $this->success('', $list);
    }

    /**
     * 获取用户地址列表
     * @param UserAddress $userAddress
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAddress(UserAddress $userAddress)
    {
        $list = $userAddress->where(['user_id' => $this->auth->getUserId()])->order('is_default desc, id desc')->select();
        $this->success('', $list);
    }

    /**
     * 获取用户地址列表
     * @param UserAddress $userAddress
     * @param $id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAddressDetail(UserAddress $userAddress, $id)
    {
        $address = $userAddress->where(['user_id' => $this->auth->getUserId(), 'id' => $id])->find();
        $this->success('', $address);
    }

    /**
     * 添加地址
     * @param UserAddress $userAddress
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveAddress(UserAddress $userAddress)
    {
        $param = $this->request->post(['id', 'username', 'mobile', 'address', 'is_default']);
        $validate = Validate::rule([
            'id' => 'number',
            'mobile' => 'mobile',
            'is_default' => 'number|between:0,1',
        ])->message([
            'id' => 'id不合法',
            'mobile' => '手机号码不合法',
            'is_default' => '是否默认参数错误',
        ]);
        if (!$validate->check($param)) $this->error($validate->getError());
        $userId = $this->auth->getUserId();
        $data = [
            'user_id' => $userId,
        ];
        foreach ($param as $k => $v) {
            if ($param[$k] && $k != 'id') {
                $data[$k] = $v;
            }
        }
        if (isset($data['is_default']) && $data['is_default'] == 1) {
            $userAddress->where(['user_id' => $userId])->update(['is_default' => 0]);
        }
        $id = (int)($param['id'] ?? 0);
        $addressData = $userAddress->where(['user_id' => $userId, 'id' => $id])->find();
        if (!$addressData) {
            $addressData = $userAddress;
        }
        $addressData->save($data);

        $list = $userAddress->where(['user_id' => $this->auth->getUserId()])->order('is_default desc, id desc')->select();
        $this->success('', $list);
    }

    public function deleteAddress($id, UserAddress $userAddress)
    {
        $userId = $this->auth->getUserId();
        $addressData = $userAddress->where(['user_id' => $userId, 'id' => $id])->find();
        if (!$addressData) {
            $this->error('数据不存在');
        }
        $addressData->delete();
        $this->success('删除成功');
    }

    /**
     * @param UserModel $userModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws InvalidConfigException
     * @throws ModelNotFoundException
     */
    public function mpLogin(UserModel $userModel)
    {
        $param = $this->request->post();
        $type = (int)($param['loginType'] ?? '');
        $code = $param['code'] ?? '';
        $iv = $param['iv'] ?? '';
        $encryptedData = $param['encryptedData'] ?? '';
        $userInfo = [];
        if ($type == 0) {
            if (!$code) $this->error('code参数错误');
            if (!$iv) $this->error('iv参数错误');
            $app = new WechatModel();
            $wechat = $app->getWechat();
            $wechatInfo = $wechat->auth->session($code);
            if (isset($wechatInfo['errcode'])) {
                $this->error($wechatInfo['errmsg']);
            }
            cache('session_key', $wechatInfo['session_key'], 7000);
            try {
                $userInfo = $wechat->encryptor->decryptData(cache('session_key'), $iv, $encryptedData);
            } catch (Exception $e) {
                $this->error('消息解密失败，请稍后再试');
            }
            $wechatInfo['openid'] = $wechatInfo['openid'] ?? '';
        } elseif ($type == 1) {
            try {
                $wechatInfo = $this->appLogin($code);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            $userInfo = [
                'nickName' => $wechatInfo['nickname'],
                'avatarUrl' => $wechatInfo['headimgurl'],
            ];
        } else {
            $this->error('登录方式错误');
        }
        $user = $userModel->where('routine_openid', $wechatInfo['openid'])->whereOr(['unionid' => $wechatInfo['unionid']])->find();
        if (!$user) {
            $user = new UserModel();
            $user->salt = Random::build('alnum', 16);
            $user->group_id = 1;
            $user->unionid = $wechatInfo['unionid'] ?? '';
            $user->routine_openid = $wechatInfo['openid'] ?? '';
            $user->username = 'wx' . date('YmdHis') . rand(1000, 9999);
            $user->nickname = $userInfo['nickName'];
            $user->mobile = '';
            $user->avatar = $userInfo['avatarUrl'];
            $user->joinip = request()->ip();
            $user->jointime = time();
            $user->password = encrypt_password(123456, $user->salt);
            $user->status = 'enable';
        }
        $this->auth->model = $user;
        $this->auth->loginSuccessful();
        unset($user['salt'], $user['password']);
        $user->token = $this->auth->getToken();
        $this->success('登录成功', ['userinfo' => $user]);
    }

    public function getOpenid(UserModel $userModel)
    {
        $code = $this->request->post('code');
        $app = new WechatModel();
        $wechat = $app->getWechat();
        $wechatInfo = $wechat->auth->session($code);
        if (isset($wechatInfo['errcode'])) {
            $this->error($wechatInfo['errmsg']);
        }
        $wechatInfo['openid'] = $wechatInfo['openid'] ?? '';
        cache('session_key', $wechatInfo['session_key'], 7000);
        $user = $userModel->where('id', $this->auth->getUserId())->find();
        if ($user['routine_openid']) {
            $this->error('您已绑定微信，禁止重复操作');
        }
        $count = $userModel->where('routine_openid', $wechatInfo['openid'])->count();
        if ($count > 0) {
            $this->error('当前微信已绑定其他用户');
        }
        $data = ['routine_openid' => $wechatInfo['openid']];
        $data['unionid'] = $wechatInfo['unionid'] ?? '';
        $user->update($data);
        $this->success('绑定微信成功');
    }

    public function buyVip(UserCard $userCard)
    {
        $id = (int)$this->request->post('id', 0);
        $channel = $this->request->post('channel', '');
        $userInfo = $this->auth->getUser();
        if ($id <= 0) $this->error('参数错误');
        $card = $userCard->find($id);
        $order = new UserCardOrder();
        $order->save([
            'order_sn' => $order->getOrderSn(),
            'user_id' => $this->auth->getUserId(),
            'card_name' => $card['name'],
            'card_price' => $card['condition'],
            'card_discount' => $card['discount'],
            'pay_time' => 0,
        ]);
        $wechat = new Wechat();
        $payment = $wechat->payment('购买会员卡', $order['order_sn'], $order['pay_price'], $userInfo['routine_openid'], $channel, 0);
        $this->success('', $payment);
    }

    public function getUserinfo()
    {
        $userinfo = $this->auth->getUser();
        $userinfo['level_info'] = UserCard::where('id', $userinfo['level'])->find();
        $this->success('', $userinfo);
    }

    public function getUserCoupon(UserCoupon $userCoupon, $goods_ids = '', $category_ids = '', $oil_price = 0)
    {
        $oil_price = (float)$oil_price;
        $type = (int)$this->request->get('type', 0);
        if (!in_array($type, [0, 1])) $this->error('参数错误');
        $page = (int)$this->request->get('page', 1);
        $page = $page <= 0 ? 1 : $page;
        $limit = (int)$this->request->get('limit', 10);
        $limit = $limit <= 0 ? 10 : $limit;
        $list = $userCoupon
            ->alias('uc')
            ->join('coupon c', 'c.id=uc.coupon_id')
            ->with(['coupon'])
            ->where('user_id', $this->auth->getUserId())
            ->when($type == 0, function (Query $query) {
                $time = time();
                $query->whereRaw("uc.updatetime=0 and IF(c.coupon_type=0, c.start_time<{$time} and c.end_time>{$time}, uc.createtime+c.days*3600*24>{$time})");
            })
            ->when($type == 1, function (Query $query) {
                $time = time();
                $query->whereRaw("uc.updatetime>0 or IF(c.coupon_type=0, c.start_time>{$time} or c.end_time<{$time}, uc.createtime+c.days*3600*24<{$time})");
            })
            ->field('c.*, uc.id as user_coupon_id')
            ->page($page)
            ->limit($limit)
            ->select()
            ->each(function ($item) use ($goods_ids, $category_ids, $oil_price) {
                $item['status'] = 0;
                $item['start'] = $item['start_time'] ? date('Y.m.d', $item['start_time']) : '';
                $item['end'] = $item['end_time'] ? date('Y.m.d', $item['end_time']) : '';
                if ($oil_price > 0) {
                    if ($oil_price >= $item['condition'] && $item['can_oil'] == 1) {
                        $item['status'] = 1;
                    }
                } else {
                    $couponGoods = explode(',', $item['goods_ids']);
                    $couponCategory = explode(',', $item['category_ids']);
                    $goods = explode(',', $goods_ids);
                    $category = explode(',', $category_ids);
                    if (
                        count(array_intersect($couponGoods, $goods)) > 0 ||
                        count(array_intersect($couponCategory, $category)) > 0 ||
                        (count($couponGoods) == 0 && count($couponCategory) == 0)
                    ) {
                        $item['status'] = 1;
                    }
                    if ($item['goods_ids']) {
                        $item['goods'] = Goods::whereIn('id', $item['goods_ids'])->column('goods_name');
                        $item['goods'] = implode('、', $item['goods']);
                    } else {
                        $item['goods'] = '全部商品可用';
                    }
                }
                return $item;
            });
        $this->success('', $list);
    }

    public function getAbout()
    {
        $this->success('', get_sys_config('about'));
    }

    /**
     * @param Coupon $coupon
     * @param $id
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCoupon(Coupon $coupon, $id)
    {
        $couponData = $coupon->where('id', $id)->find();
        if (!$couponData || $couponData->isEmpty()) $this->error('优惠券不存在');

        $userCoupon = new UserCoupon();
        $has = $userCoupon->where(['user_id' => $this->auth->getUserId(), 'coupon_id' => $couponData->id])->count();
        if ($has > 0) $this->error('禁止重复领取');
        $userCoupon->save([
            'user_id' => $this->auth->getUserId(),
            'coupon_id' => $couponData->id,
            'updatetime' => 0,
        ]);

        $this->success('领取成功');
    }

    public function appLogin($code)
    {
        $appid = get_sys_config('third_appid');
        $appsecret = get_sys_config('third_appsecret');
        $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code={$code}&grant_type=authorization_code";
        $token_info = $this->https_request($get_token_url);
        $token_info = json_decode($token_info, true);
        if (isset($token_info['errcode'])) {
            throw new ValidateException(json_encode($token_info, 256));
        }
        $get_userinfo_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $token_info['access_token'] . '&openid=' . $token_info['openid'] . '&lang=zh_CN';
        $userinfo = $this->https_request($get_userinfo_url);
        $userinfo = json_decode($userinfo, true);
        if (isset($userinfo['errcode'])) {
            throw new ValidateException(json_encode($userinfo, 256));
        }
        return $userinfo;
    }

    public function https_request($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        //参数为1表示传输数据，为0表示直接输出显示。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //参数为0表示不带头文件，为1表示带头文件
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 关闭SSL验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $output = curl_exec($ch);
        if (curl_exec($ch) === false) {
            throw new ValidateException('Curl error: ' . curl_error($ch));
        }
        curl_close($ch);
        return $output;
    }

    public function bind(UserModel $user, $mobile, $code, $password)
    {
        $cache = cache('bind' . $mobile);
        if ($cache != $code) $this->error('验证码错误，请重新发送');
        // 删除缓存
        cache('register' . $mobile, null);
        $salt = Random::build('alnum', 16);
        $password = encrypt_password($password, $salt);
        $user->where('id', $this->auth->getUserId())->update([
            'mobile' => $mobile,
            'password' => $password,
            'salt' => $salt,
        ]);
    }

    /**
     * @param Coupon $coupon
     * @param UserCoupon $userCoupon
     * @return void
     * @throws Exception
     */
    public function shared(Coupon $coupon, UserCoupon $userCoupon)
    {
        $time = time();
        $giveCoupons = $coupon
            ->whereRaw("(coupon_type = 0 && start_time < {$time} && end_time > {$time}) or coupon_type=1")
            ->where('share', 1)
            ->column('id');
        $uc = [];
        foreach ($giveCoupons as $id) {
            $uc[] = [
                'user_id' => $this->auth->getUserId(),
                'coupon_id' => $id,
                'updatetime' => 0,
            ];
        }
        $userCoupon->saveAll($uc);
        $this->success('操作成功');
    }

    /**
     * @param UserScoreLog $scoreLog
     * @return void
     * @throws DbException
     */
    public function signIn(UserScoreLog $scoreLog)
    {
        $userId = $this->auth->getUserId();
        $start = strtotime(date('Y-m-d'));
        $end = $start + 3600 * 24;
        if ($scoreLog->where('user_id', $userId)->whereBetween('createtime', [$start, $end])->count() > 0) {
            $this->error('今日已签到，请勿重复签到');
        }
        $data = [
            'user_id' => $userId,
            'score' => 5,
            'memo' => '签到成功',
        ];
        $scoreLog->save($data);
        $user = $this->auth->getUser();
        $this->success('签到成功', ['score' => $user->score]);
    }

    public function withdrawal(Withdrawal $withdrawal, UserMoneyLog $moneyLog, Card $card)
    {
        $data = $this->request->post();
        $user = $this->auth->getUser();
        $data['user_id'] = $user->id;
        $data['money'] = floatval($data['money']);
        Db::startTrans();
        try {
            $max = (float)get_sys_config('max_withdrawal');
            $min = (float)get_sys_config('min_withdrawal');
            $way = trim($data['way']);
            $cardId = (int)($data['card_id'] ?? 0);
            if (!in_array($way, ['wechat', 'alipay', 'card'])) throw new ValidateException('提现方式错误，请重新选择');
            if ($way == 'card' && !$cardId) {
                throw new ValidateException('请选择提现银行卡');
            }
            if ($way == 'card') {
                $cardInfo = $card->where(['user_id' => $data['user_id'], 'id' => $cardId])->find();
                if (!$cardInfo || $cardInfo->isEmpty()) throw new ValidateException('银行卡信息错误，请重新选择');
                $data['card_info'] = json_encode($cardInfo, 256);
            }
            if ($max > 0 && $data['money'] > $max) throw new ValidateException('超出提现范围');
            if ($max > 0 && $data['money'] < $min) throw new ValidateException('超出提现范围');
            $times = (int)get_sys_config('withdrawal_times');
            $utimes = $withdrawal->where('user_id', $user['id'])->whereIn('state', [0, 1])->count();
            if ($utimes >= $times) throw new ValidateException("一天做多能提现{$times}次");
            if ($data['money'] <= 0) throw new ValidateException('请输入有效的提现金额');
            if ($data['money'] > $user['money']) throw new ValidateException('余额不足');
            $data['before'] = $data['money'];
            $data['after'] = bcsub($user['money'], $data['money'], 2);
            $ratio = get_sys_config('withdrawal_ratio');
            if (strstr($ratio, '%')) {
                $ratio = str_replace('%', '', $ratio);
                $data['ratio'] = bcmul($data['money'], $ratio / 100, 2);
            } else {
                $data['ratio'] = floatval($ratio);
            }
            $data['receive'] = bcsub($data['money'], $data['ratio'], 2);
            if ($data['receive'] <= 0) throw new ValidateException('超出提现范围');
            $withdrawal->save($data);
            $moneyLog->create([
                'user_id' => $user->id,
                'money' => -$data['money'],
                'memo' => '提现',
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('申请成功，请等待审核');
    }

    public function cancelWithdrawal(Withdrawal $withdrawal, UserMoneyLog $moneyLog)
    {
        $id = (int)$this->request->post('id');
        $userId = $this->auth->getUserId();
        Db::startTrans();
        try {
            $withdrawal = $withdrawal->where(['user_id' => $this->auth->getUserId(), 'id' => $id])->find();
            if (!$withdrawal || $withdrawal->isEmpty()) throw new ValidateException('数据不存在');
            $withdrawal->state = 3;
            $withdrawal->save();
            $moneyLog->create([
                'user_id' => $userId,
                'money' => $withdrawal->money,
                'memo' => '取消提现',
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('申请成功，请等待审核');
    }

    /**
     * @param $refresh
     * @return void
     */
    public function poster($refresh = 0)
    {
        $background = app()->getRootPath() . '/public/storage/default/20220807/7994fc93ebcb6f615fc49fd91abe1083acfc5c5f.jpeg';
        $poster = '/storage/poster/' . $this->auth->getUserId() . '.png';
        $result = PosterManager::Poster(app()->getRootPath() . '/public' . $poster) //生成海报，这里写保存路径和文件名，可以指定图片后缀。默认png
        ->buildIm(638, 826, [255, 255, 255, 127], false)
            ->buildImage('https://test.acyapi.51acy.com/wechat/poster/top_bg.png')
            ->buildImage('https://test.acyapi.51acy.com/wechat/poster/half_circle.png', 254, 321)
            ->buildImage($background, 253, 326, 0, 0, 131, 131, false, 'circle')
            ->buildImage('https://test.acyapi.51acy.com/wechat/poster/fengexian.png', 0, 655)
            ->buildText('苏 轼', 'center', 477, 16, [51, 51, 51, 1])
            ->buildText('明月几时有，把酒问青天。不知天上宫阙，今夕是何年。', 'center', 515, 14, [53, 53, 53, 1])
            ->buildText('我欲乘风归去，又恐琼楼玉宇，高处不胜寒。', 'center', 535, 14, [53, 153, 153, 1])
            ->buildText('起舞弄清影，何似在人间。转朱阁，低绮户，照无眠。', 'center', 555, 14, [53, 153, 153, 1])
            ->buildText('不应有恨，何事长向别时圆？', 'center', 575, 14, [53, 153, 153, 1])
            ->buildText('人有悲欢离合，月有阴晴圆缺，此事古难全。', 'center', 595, 14, [53, 153, 153, 1])
            ->buildText('但愿人长久，千里共婵娟。', 'center', 615, 14, [53, 153, 153, 1])
            ->buildText('长按识别', 497, 720, 15, [53, 153, 153, 1])
            ->buildText('查看TA的更多作品', 413, 757, 15, [53, 153, 153, 1])
            ->buildQr('http://www.520yummy.com', 37, 692, 0, 0, 0, 0, 4, 1)
            ->getPoster();
        $this->success('', ['poster' => full_url($poster)]);
    }

    /**
     * @param Card $cardModel
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function bankcard(Card $cardModel)
    {
        $data = $this->request->post();
        $userId = $this->auth->getUserId();
        $id = (int)($data['id'] ?? '');
        $card = $cardModel->where(['user_id' => $userId, 'id' => $id])->find();
        if (!$card || $card->isEmpty()) $card = new Card();
        if ($card->where([['id', '<>', $id], ['number', '=', $data['number']]])->count() > 0) {
            $this->error('该卡号已存在，请核对后重试');
        }
        unset($data['id']);
        $data['user_id'] = $userId;
        $card->save($data);

        $this->success('操作成功', $card);
    }

    /**
     * @param Card $cardModel
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delcard(Card $cardModel)
    {
        $id = (int)$this->request->post('id');
        $userId = $this->auth->getUserId();
        $card = $cardModel->where(['user_id' => $userId, 'id' => $id])->find();
        if (!$card || $card->isEmpty()) $this->error('数据不存在');
        $card->delete();

        $this->success('操作成功');
    }

    /**
     * @param Card $card
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function cardList(Card $card)
    {
        $page = (int)$this->request->get('page', 1);
        $page = $page <= 0 ? 1 : $page;
        $limit = (int)$this->request->get('limit', 10);
        $limit = $limit <= 0 ? 10 : $limit;
        $list = $card->where('user_id', $this->auth->getUserId())
            ->page($page)
            ->limit($limit)
            ->hidden(['createtime', 'updatetime', 'delete_time'])
            ->select();
        $this->success('', $list);
    }
}